#include "appender.h"
#include <QDebug>

static bool appendByteFromNumber(QDataStream &stream, const QString &number, int system)
{
    bool ok = true;
    quint8 b = (quint8)number.toInt(&ok, system);
    if (!ok) {
        return false;
    }
    stream << b;
    return true;
}

CAppender::CAppender(QByteArray *bytes)
{
    m_stream = new QDataStream(bytes, QIODevice::Append);
}

CAppender::~CAppender()
{
    delete m_stream;
}

bool CAppender::appendUInt8(quint8 number)
{
    *m_stream << number;
    return true;
}

bool CAppender::appendUInt16(quint16 number)
{
    *m_stream << number;
    return true;
}

bool CAppender::appendUInt32(quint32 number)
{
    *m_stream << number;
    return true;
}

bool CAppender::appendUInt8(const QString &number)
{
    bool ok = false;
    quint8 v = number.toInt(&ok, 0);
    if (!ok) {
        return false;
    }
    return appendUInt8(v);
}

bool CAppender::appendUInt16(const QString &number)
{
    bool ok = false;
    quint16 v = number.toInt(&ok, 0);
    if (!ok) {
        return false;
    }
    return appendUInt16(v);
}

bool CAppender::appendUInt32(const QString &number)
{
    bool ok = false;
    quint32 v = number.toInt(&ok, 0);
    if (!ok) {
        return false;
    }
    return appendUInt32(v);
}

bool CAppender::appendBin(const QString &number)
{
    int from = 0;
    int width = 8;
    int system = 2;

    int first = number.length()%width;
    if (first != 0) {
        return false;
    }
    for (; from < number.length(); from += width) {
        if (!appendByteFromNumber(*m_stream, number.mid(from, width), system)) {
            return false;
        }
    }
    return true;
}

bool CAppender::appendHex(const QString &number)
{
    int from = 0;
    int width = 2;
    int system = 16;

    int first = number.length()%width;
    if (first != 0) {
        return false;
    }
    for (; from < number.length(); from += width) {
        if (!appendByteFromNumber(*m_stream, number.mid(from, width), system)) {
            return false;
        }
    }
    return true;
}

bool CAppender::appendSepDec(const QString &number,
                         const QString &sep, int tokc)
{
    for (int from = 0; from < number.length();) {
        int pos = number.indexOf(sep, from);
        if (pos == -1) {
            pos = number.length();
        }

        int length = pos - from;
        QString tok = number.mid(from, length);
        if (!appendByteFromNumber(*m_stream, tok, 10)) {
            return false;
        }

        tokc--;
        from = pos + sep.length();
    }
    if (tokc != 0) {
        return false;
    }
    return true;
}
